package com.liwy3.thread;

import lombok.SneakyThrows;

/**
 * Copyright © 2022年10月19日 北京自如信息科技有限公司. All rights reserved.
 *
 * @Prject: liwy3
 * @Package: com.liwy3.thread
 * @Description: 实现生产者消费者
 * @author: Crazy4J
 * @date: 2022年10月19日 11:23
 * @version: V1.0
 */
public class ProduceConsumer {

    public static Integer count = 0;
    public static final Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new Produce()).start();
        new Thread(new Consumer()).start();
    }

    static class Produce implements Runnable {

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                Thread.sleep(1000);
                synchronized (lock) {
                    count++;
                    if (count > 0) {
                        lock.notifyAll();
                    }
                    System.out.println(Thread.currentThread().getName() + "生产数目：" + count);
                }
            }
        }
    }

    static class Consumer implements Runnable {

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                Thread.sleep(3000);
                synchronized (lock) {
                    if (count <= 0) {
                        lock.wait();
                    }
                    System.out.println(Thread.currentThread().getName() + "===============消费数目：" + count--);
                }

            }
        }
    }

}
